package com.mdb.open.trade.service.trade;


/*
* Copyright (C), 2017-2019 澳发科技(MDB)
* FileName: TfMerchantBankAccountService.java
* Author:   you.yichao
* Date:     2019-09-20
* History:
* <author>          <time>          <version>          <desc>
* you.yichao         2019-09-20          V1.00             代码生成器初始生成代码
* -----------------------------------------------------------
* 作者姓名           修改时间           版本号            描述
*/


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.mdb.bc.api.data.ListResultEx;
import com.mdb.bc.api.data.ResultEx;
import com.mdb.bc.api.enums.OrderByEnum;
import com.mdb.bc.cache.sequence.util.SequenceGenerator;
import com.mdb.bc.database.mybatisplus.PageUtil;
import com.mdb.bc.database.mybatisplus.SuperService;
import com.mdb.bc.utils.BeanConvertUtil;
import com.mdb.bc.utils.ObjectUtil;
import com.mdb.enums.PlatformRetCodeEnum;
import com.mdb.open.common.enums.DataChannelEnum;
import com.mdb.open.common.enums.TfSequenceEnum;
import com.mdb.open.common.enums.TradeWebErrorCodeEnum;
import com.mdb.open.common.enums.trade.status.BankAccountRecordStatusEnum;
import com.mdb.open.common.enums.trade.type.MerBankAccDefaultTypeEnum;
import com.mdb.open.trade.common.MdbDataSource;
import com.mdb.open.trade.config.TradeOpenProperties;
import com.mdb.open.trade.constant.trade.Fields;
import com.mdb.open.trade.domain.bo.trade.GetMerBankAccByDetailBo;
import com.mdb.open.trade.domain.bo.trade.QueryMerchantBankAccountBo;
import com.mdb.open.trade.domain.bo.trade.SetDefaultMerBankAccBo;
import com.mdb.open.trade.domain.dto.trade.QueryMerchantBankAccountDto;
import com.mdb.open.trade.domain.ko.trade.MerchantBankAccCntKo;
import com.mdb.open.trade.domain.po.trade.MerchantBankAccount;
import com.mdb.open.trade.domain.po.trade.MerchantInfo;
import com.mdb.open.trade.domain.vo.trade.MerchantBankAccountVo;
import com.mdb.open.trade.mapper.trade.TfMerchantBankAccountMapper;
import com.mdb.open.trade.mapper.trade.TfMerchantInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类描述：
 *  商户收款账号表 服务类
 *
 * @author you.yichao
 * @date 2019-09-20
 */
@Service
@DS(MdbDataSource.TRADE)
public class TfMerchantBankAccountService extends SuperService<TfMerchantBankAccountMapper, MerchantBankAccount> {

    @Autowired
    TfMerchantInfoMapper tfMerchantInfoMapper;

    @Autowired
    SequenceGenerator sequenceGenerator;

    @Autowired
    TradeOpenProperties tradeOpenProperties;


    public ResultEx<MerchantBankAccount> getMerBankAccByDetail(GetMerBankAccByDetailBo bo) {

        //判断收款账号数是否达到上限
        String merchantNo = bo.getMerchantNo();

        int cnt = this.countByMerchantNo(bo.getCustomerCode(), merchantNo, BankAccountRecordStatusEnum.ENABLE);
        if (Boolean.TRUE.equals(cnt >= tradeOpenProperties.getAccountCount())) {
            return ResultEx.fail("收款账户不能超过5个，请到开放平台维护");
        }
        //校验批量新增的收款账号是否重复（包括新增待插入的记录）
        cnt = this.countByMerchantNo(bo.getMerchantNo(), bo.getAccNo(), bo.getCustomerCode());
        if (cnt > 0) {
            return ResultEx.makeResult(PlatformRetCodeEnum.ACCOUNT_REPEAT);
        }

        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(MerchantBankAccount::getAccNo, bo.getAccNo());
        queryWrapper.eq(MerchantBankAccount::getRecevSwiftCode, bo.getRecevSwiftCode());
        queryWrapper.eq(MerchantBankAccount::getIntermediarySwiftCode, bo.getIntermediarySwiftCode());
        queryWrapper.eq(MerchantBankAccount::getAccCnName, bo.getAccCnName());
        queryWrapper.eq(MerchantBankAccount::getAccEnName, bo.getAccEnName());

        MerchantBankAccount account = this.baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(account)) {
            MerchantBankAccount merchantBankAccount = new MerchantBankAccount();
            merchantBankAccount.setDefaultType(MerBankAccDefaultTypeEnum.NORMAL);
            merchantBankAccount.setAccUniqueNo(sequenceGenerator.generator(TfSequenceEnum.MERCHANT_BANK_ACC_UNIQUE_NO.setDataChannelEnum(DataChannelEnum.API)));
            merchantBankAccount.setCustomerCode(bo.getCustomerCode());
            merchantBankAccount.setStatus(BankAccountRecordStatusEnum.ENABLE);
            merchantBankAccount.setCustomerName(bo.getCustomerName());
            merchantBankAccount.setMerchantNo(bo.getMerchantNo());
            merchantBankAccount.setMerchantName(bo.getMerchantName());
            merchantBankAccount.setMerchantType(bo.getMerchantType());
            merchantBankAccount.setMerchantIdNo(bo.getMerchantIdNo());
            merchantBankAccount.setReceiveAddressEn(bo.getReceiveAddressEn());
            merchantBankAccount.setRecevSwiftCode(bo.getRecevSwiftCode());
            merchantBankAccount.setIntermediarySwiftCode(bo.getIntermediarySwiftCode());
            merchantBankAccount.setAccCnName(bo.getAccCnName());
            merchantBankAccount.setAccNo(bo.getAccNo());
            merchantBankAccount.setAccEnName(bo.getAccEnName());

            int count = this.baseMapper.insert(merchantBankAccount);
            if(count != 1) {
                return ResultEx.fail();
            }
            return ResultEx.ok(merchantBankAccount);
        }

        return ResultEx.ok(account);

    }

    /**
     * 根据自定义条件查询所有商户列表（可分页）
     */
    public ListResultEx<MerchantBankAccountVo> selectPageByCondition(QueryMerchantBankAccountBo bo) {
        bo.setOrder(OrderByEnum.DESC);
        bo.setSort(Fields.UPDATE_TIME);

        LambdaQueryWrapper<MerchantInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantInfo::getCustomerCode, bo.getCustomerCode());
        if (ObjectUtil.isNotEmpty(bo.getMerchantNo())) {
            queryWrapper.eq(MerchantInfo::getMerchantNo, bo.getMerchantNo());
        }
        if (ObjectUtil.isNotEmpty(bo.getMerchantName())) {
            queryWrapper.like(MerchantInfo::getMerchantNameCn, bo.getMerchantName());
        }
        if (ObjectUtil.isNotEmpty(bo.getMerchantType())) {
            queryWrapper.eq(MerchantInfo::getMerchantType, bo.getMerchantType());
        }

        IPage<MerchantBankAccCntKo> pageList = tfMerchantInfoMapper.merchantBankAccCntList(PageUtil.initPage(bo), queryWrapper);

        List<MerchantBankAccountVo> resultList = BeanConvertUtil.convertList(pageList.getRecords(), ko -> {
            MerchantBankAccountVo vo = new MerchantBankAccountVo();
            vo.setCustomerCode(ko.getCustomerCode());
            vo.setCustomerName(ko.getCustomerName());
            vo.setMerchantNo(ko.getMerchantNo());
            vo.setMerchantName(ko.getMerchantNameCn());
            vo.setMerchantType(ko.getMerchantType());
            vo.setMerchantIdNo(ko.getMerchantCertNumber());
            vo.setCreateTime(ko.getCreateTime());
            vo.setUpdateTime(ko.getUpdateTime());
            vo.setAccCount(ko.getAccCount());
            return vo;
        });

        return ListResultEx.ok(resultList, pageList.getTotal(), pageList.getCurrent(), pageList.getSize());
    }


    /**
     * 根据商户编号查询所有商户分页列表
     */
    public Integer countByMerchantNo(String customerCode, String merchantNo, BankAccountRecordStatusEnum statusEnum) {
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(customerCode)) {
            queryWrapper.eq(MerchantBankAccount::getCustomerCode, customerCode);
        }
        if (ObjectUtil.isNotEmpty(merchantNo)) {
            queryWrapper.eq(MerchantBankAccount::getMerchantNo, merchantNo);
        }
        if (ObjectUtil.isNotEmpty(statusEnum)) {
            queryWrapper.eq(MerchantBankAccount::getStatus, statusEnum);
        }

        return this.baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据商户编号查询所有商户分页列表
     */
    public Integer countByMerchantNo(String merchantNo, String accNo, String customerCode) {
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::getMerchantNo, merchantNo);
        queryWrapper.eq(MerchantBankAccount::getAccNo, accNo);
        queryWrapper.eq(MerchantBankAccount::getCustomerCode, customerCode);
        queryWrapper.eq(MerchantBankAccount::isDeleted, BankAccountRecordStatusEnum.ENABLE);

        return this.baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据商户编号 查询指定客户下对应商户 的收款账号列表
     * 那更新时间倒叙排序
     */
    public ListResultEx<MerchantBankAccount> queryMerchantAccountListByMerNo(QueryMerchantBankAccountDto dto){
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::isDeleted, BankAccountRecordStatusEnum.ENABLE);
        queryWrapper.eq(MerchantBankAccount::getMerchantNo, dto.getMerchantNo());
        queryWrapper.eq(MerchantBankAccount::getCustomerCode, dto.getCustomerCode());
        queryWrapper.orderByDesc(MerchantBankAccount::getUpdateTime);

        return ListResultEx.ok(this.baseMapper.selectList(queryWrapper));

    }

    /**
     * 根据客户编号 查询默认对应商户 的收款账号
     * 那id正序排
     */
    public ListResultEx<MerchantBankAccount> queryCusDefaultMerBankAcc(String customerCode){

        List<MerchantBankAccount> resultList = Lists.newArrayList();
        MerchantInfo merchantInfo = tfMerchantInfoMapper.selectOne(new LambdaQueryWrapper<MerchantInfo>()
                .eq(MerchantInfo::getCustomerCode, customerCode)
                .eq(MerchantInfo::isDefaultStatus, true));
        if (ObjectUtil.isEmpty(merchantInfo)) {
            return ListResultEx.ok(resultList);
        }

        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::getStatus, BankAccountRecordStatusEnum.ENABLE);
        queryWrapper.eq(MerchantBankAccount::getCustomerCode, customerCode);
        queryWrapper.eq(MerchantBankAccount::getMerchantNo, merchantInfo.getMerchantNo());
        queryWrapper.orderByAsc(MerchantBankAccount::getId);

        return ListResultEx.ok(this.baseMapper.selectList(queryWrapper));
    }

    /**
     * 根据收款账号记录编号获取详情
     */
    public ResultEx<MerchantBankAccount> getAccountInfoByAccUniNo(String accNo, String customerCode){
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::getAccUniqueNo, accNo);
        queryWrapper.eq(MerchantBankAccount::getCustomerCode, customerCode);
        queryWrapper.eq(MerchantBankAccount::isDeleted, Boolean.FALSE);

        return ResultEx.ok(this.baseMapper.selectOne(queryWrapper));
    }

    /**
     * 根据收款账号记录编号获取详情
     */
    public ResultEx<MerchantBankAccount> getAccountInfoByAccUniNo(String accNo, String customerCode, String merchantNo){
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::getAccUniqueNo, accNo);
        queryWrapper.eq(MerchantBankAccount::getMerchantNo, merchantNo);
        queryWrapper.eq(MerchantBankAccount::getCustomerCode, customerCode);
        queryWrapper.eq(MerchantBankAccount::isDeleted, Boolean.FALSE);

        return ResultEx.ok(this.baseMapper.selectOne(queryWrapper));
    }

    public ResultEx updateMerchantAccount(MerchantBankAccount merchantBankAccount) {

        LambdaUpdateWrapper<MerchantBankAccount> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MerchantBankAccount::getAccUniqueNo, merchantBankAccount.getAccUniqueNo());

        MerchantBankAccount updateAccount = new MerchantBankAccount();
        updateAccount.setAccCnName(merchantBankAccount.getAccCnName());
        updateAccount.setAccEnName(merchantBankAccount.getAccEnName());
        updateAccount.setReceiveAddressCn(merchantBankAccount.getReceiveAddressCn());
        updateAccount.setReceiveAddressEn(merchantBankAccount.getReceiveAddressEn());
        updateAccount.setAccNo(merchantBankAccount.getAccNo());
        updateAccount.setAccBranch(merchantBankAccount.getAccBranch());
        updateAccount.setRecevSwiftCode(merchantBankAccount.getRecevSwiftCode());
        updateAccount.setIntermediarySwiftCode(merchantBankAccount.getIntermediarySwiftCode());
        updateAccount.setDefaultType(merchantBankAccount.getDefaultType());
        if (MerBankAccDefaultTypeEnum.DEFAULT.equals(merchantBankAccount.getDefaultType())) {
            MerchantBankAccount account = new MerchantBankAccount();
            account.setDefaultType(MerBankAccDefaultTypeEnum.NORMAL);

            this.baseMapper.update(account, new LambdaUpdateWrapper<MerchantBankAccount>()
                    .eq(MerchantBankAccount::getMerchantNo, merchantBankAccount.getMerchantNo())
                    .eq(MerchantBankAccount::getCustomerCode, merchantBankAccount.getCustomerCode()));
        }

        int cnt = this.baseMapper.update(updateAccount, updateWrapper);
        if (cnt != 1) {
            return ResultEx.fail();
        }

        return ResultEx.ok();
    }

    public ResultEx setDefaultBankAcc(SetDefaultMerBankAccBo bo) {

        MerchantBankAccount account = new MerchantBankAccount();
        account.setDefaultType(MerBankAccDefaultTypeEnum.NORMAL);

        this.baseMapper.update(account, new LambdaUpdateWrapper<MerchantBankAccount>()
                .eq(MerchantBankAccount::getMerchantNo, bo.getMerchantNo())
                .eq(MerchantBankAccount::getCustomerCode, bo.getCustomerCode()));

        MerchantBankAccount defaultAcc = new MerchantBankAccount();
        defaultAcc.setDefaultType(MerBankAccDefaultTypeEnum.DEFAULT);
        int count = this.baseMapper.update(defaultAcc, new LambdaUpdateWrapper<MerchantBankAccount>()
                .eq(MerchantBankAccount::getMerchantNo, bo.getMerchantNo())
                .eq(MerchantBankAccount::getCustomerCode, bo.getCustomerCode())
                .eq(MerchantBankAccount::getAccUniqueNo, bo.getAccUniqueNo()));

        if (count != 1) {
            return ResultEx.fail(TradeWebErrorCodeEnum.UPDATE_ACCOUNT_FAIL.getText());
        }
        return ResultEx.ok();
    }

    /**
     * 根据商户号更新对应商户对应的收款账号中商户相关的信息
     */
    public ResultEx delete(String accUniqueNo) {
        LambdaQueryWrapper<MerchantBankAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MerchantBankAccount::getAccUniqueNo, accUniqueNo);
        int result = this.baseMapper.delete(queryWrapper);
        if(result != 1){
            return ResultEx.fail();
        }

        return ResultEx.ok();
    }
}
